import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/ui.dart';

class InformationIndoorPointPage extends StatefulWidget {
  const InformationIndoorPointPage({super.key});

  @override
  State<InformationIndoorPointPage> createState() =>
      _InformationIndoorPointPageState();
}

class _InformationIndoorPointPageState
    extends State<InformationIndoorPointPage> {
  RefreshController refreshController = RefreshController();
  ListPaginationModel pagination = ListPaginationModel();
  List<dynamic> list = List.filled(20, {}).toList();
  String keyword = '';
  fetchData() async {
    var res = await Http.instance.post(
      '/api/information/indoor/temperature',
      data: {
        'page': pagination.currentPage,
        'keyword': keyword,
      },
    );
    if (res.code == 1) {
      if (pagination.currentPage <= 1) {
        list.clear();
      }
      pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => list.add(item),
      );
    }
    setState(() {});
    refreshController.refreshCompleted();
    if (pagination.hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      dismissOnCapturedTaps: true,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('室温监测'),
        ),
        body: UiLifeCycle(
            onRouteDone: () {
              fetchData();
            },
            child: Column(
              children: [
                Container(
                  color: Theme.of(context).appBarTheme.backgroundColor,
                  padding: const EdgeInsets.only(
                    top: UiTheme.toolbarSpacing,
                    left: UiTheme.spacingX,
                    right: UiTheme.spacingX,
                    bottom: UiTheme.spacingX,
                  ),
                  alignment: Alignment.centerLeft,
                  child: UiSearchBar(
                    placeholder: '搜索企业或监测位置',
                    onSubmitted: (val) {
                      keyword = val;
                      pagination.currentPage = 1;
                      fetchData();
                    },
                    onClear: () {
                      keyword = '';
                      pagination.currentPage = 1;
                      fetchData();
                    },
                  ),
                ),
                const Divider(height: 0),
                Expanded(
                  child: UiPushToRefresh(
                    controller: refreshController,
                    onRefresh: () {
                      pagination.currentPage = 1;
                      fetchData();
                    },
                    enablePullUp:
                        pagination.lastPage > 1 && !refreshController.isRefresh,
                    onLoad: () {
                      pagination.currentPage++;
                      fetchData();
                    },
                    child: ListView.builder(
                      itemBuilder: (context, index) {
                        var item = list[index];
                        bool isBlock = item['id'] == null;
                        return UiPanel(
                          margin: const EdgeInsets.only(
                            left: UiTheme.spacingX,
                            right: UiTheme.spacingX,
                            top: UiTheme.spacingX,
                          ),
                          padding: const EdgeInsets.all(UiTheme.spacing),
                          child: Row(children: [
                            Expanded(
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  isBlock
                                      ? const UiBlock(
                                          height: 20,
                                          width: 250,
                                        )
                                      : Text(
                                          item['point_name'] ?? '',
                                          style: const TextStyle(
                                            fontSize: 18,
                                            fontWeight: FontWeight.bold,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ),
                                  const SizedBox(height: 5),
                                  isBlock
                                      ? const UiBlock(
                                          height: 15,
                                          width: 150,
                                          margin: 4,
                                        )
                                      : Row(
                                          children: [
                                            const Icon(UiIcons.company,
                                                size: 15),
                                            const SizedBox(width: 5),
                                            Text(
                                              item['company_name'] ?? '',
                                            ),
                                          ],
                                        )
                                ],
                              ),
                            ),
                            const SizedBox(width: 30),
                            isBlock
                                ? Container()
                                : Text(
                                    '${item['temper']}­°C',
                                    style: TextStyle(
                                      color: item['status'] == 'abnormal'
                                          ? Colors.red
                                          : null,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                          ]),
                        );
                      },
                      itemCount: list.length,
                    ),
                  ),
                ),
              ],
            )),
      ),
    );
  }
}
